// pages/shopping-cart/shopping-cart.js
const app = getApp()
const { request } = require("../../utils/request")

Page({
  data: {
    urlPath: "",
    cartList: [],
    allChecked: false,
    totalPrice: 0,
    checkedCount: 0,
  },

  getPath() {
    try {
      const tokenName = wx.getStorageSync("tokenName")
      console.log("tokenName:", tokenName)
      if (tokenName === "usertoken") {
        this.setData({ urlPath: "employee" })
      } else if (tokenName === "admintoken") {
        this.setData({ urlPath: "admin" })
      } else {
        this.setData({ urlPath: "sadmin" })
      }
    } catch (e) {
      console.error("获取 tokenName 失败:", e)
      // this.setData({ urlPath: "sadmin" }); // 默认值
    }
  },

  onLoad() {
    this.getPath()
    this.loadCartData()
  },

  // 加载购物车数据
  loadCartData() {
    const { urlPath } = this.data
    const id = wx.getStorageSync("userId")
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/carts/search/${id}`,
      method: "GET",
    })
      .then((res) => {
        if (res.data.code === 1) {
          this.setData(
            {
              cartList: res.data.data,
            },
            () => {
              this.calculateTotal()
            },
          )
        }
      })
      .catch(() => wx.showToast({ title: "网络错误", icon: "none" }))
  },

  // 切换选中状态
  toggleCheck(e) {
    const index = e.currentTarget.dataset.index
    const key = `cartList[${index}].checked`
    const { urlPath } = this.data
    this.setData({
      [key]: !this.data.cartList[index].checked,
    })
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/carts/update`,
      method: "POST",
      data: this.data.cartList[index],
    }).catch(() => wx.showToast({ title: "网络错误", icon: "none" }))
    this.calculateTotal()
  },

  // 修改商品数量
  changeCount(e) {
    const { index, type } = e.currentTarget.dataset
    const cartList = this.data.cartList
    const count = cartList[index].count + Number.parseInt(type)
    const { urlPath } = this.data
    if (count < 1) return
    cartList[index].count = count
    this.setData({ cartList })
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/carts/update`,
      method: "POST",
      data: cartList[index],
    }).catch(() => wx.showToast({ title: "网络错误", icon: "none" }))
    this.calculateTotal()
  },

  // 全选/反选
  toggleAll() {
    const allChecked = !this.data.allChecked
    const cartList = this.data.cartList.map((item) => ({
      ...item,
      checked: allChecked,
    }))
    const { urlPath } = this.data
    this.setData({
      cartList,
      allChecked,
    })
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/carts/updates`,
      method: "POST",
      data: cartList,
    }).catch(() => wx.showToast({ title: "网络错误", icon: "none" }))
    this.calculateTotal()
  },

  // 计算总价和选中数量
  calculateTotal() {
    let total = 0
    let count = 0
    let allChecked = true
    this.data.cartList.forEach((item) => {
      if (item.checked) {
        total += item.price * item.count
        count++
      } else {
        allChecked = false
      }
    })

    this.setData({
      totalPrice: total.toFixed(2),
      checkedCount: count,
      allChecked,
    })
  },

  // 删除单个商品
  deleteItem(e) {
    const id = wx.getStorageSync("userId")
    const index = e.currentTarget.dataset.index
    const itemId = this.data.cartList[index].id
    const { urlPath } = this.data
    wx.showModal({
      title: "提示",
      content: "确定要删除该商品吗？",
      success: (res) => {
        if (res.confirm) {
          request({
            url: `${app.globalData.baseUrl}/${urlPath}/carts/delete?id=${id}&itemId=${itemId}`,
            method: "DELETE",
          })
            .then((res) => {
              if (res.data.code === 1) {
                this.setData(
                  {
                    cartList: res.data.data,
                  },
                  () => {
                    this.calculateTotal()
                  },
                )
                wx.showToast({ title: "删除成功" })
              }
            })
            .catch(() => wx.showToast({ title: "删除失败", icon: "none" }))
        }
      },
    })
  },

  // 批量删除选中商品
  deleteSelected() {
    const id = wx.getStorageSync("userId")
    const { urlPath } = this.data
    if (this.data.checkedCount === 0) {
      wx.showToast({ title: "请先选择商品", icon: "none" })
      return
    }

    wx.showModal({
      title: "提示",
      content: `确定要删除选中的${this.data.checkedCount}件商品吗？`,
      success: (res) => {
        if (res.confirm) {
          const selectedIds = this.data.cartList.filter((item) => item.checked).map((item) => item.id)

          request({
            url: `${app.globalData.baseUrl}/${urlPath}/carts/delete/batch?id=${id}`,
            method: "DELETE",
            data: selectedIds,
          })
            .then((res) => {
              if (res.data.code === 1) {
                this.setData(
                  {
                    cartList: res.data.data,
                  },
                  () => {
                    this.calculateTotal()
                  },
                )
                wx.showToast({ title: "删除成功" })
              }
            })
            .catch(() => wx.showToast({ title: "删除失败", icon: "none" }))
        }
      },
    })
  },

  // 去结算
  handleCheckout() {
    const { urlPath } = this.data
    if (this.data.checkedCount === 0) {
      wx.showToast({ title: "请选择商品", icon: "none" })
      return
    }
    const result = []
    const id = wx.getStorageSync("userId")
    this.data.cartList.forEach((item) => {
      if (item.checked) {
        result.push(item)
      }
    })
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/carts/payment?id=${id}`,
      method: "POST",
      data: result,
    })
      .then((res) => {
        console.log(res)
        if (res.statusCode === 200) {
          this.setData(
            {
              cartList: res.data.data.shoppingCarts,
            },
            () => {
              this.calculateTotal()
              wx.navigateTo({
                url: `/pages/order/order?id=${res.data.data.id}`,
              })
            },
          )
          wx.showToast({ title: "结算成功" })
        }
      })
      .catch(() => wx.showToast({ title: "网络错误", icon: "none" }))
  },

  onShow() {
    this.getTabBar().init()
    this.loadCartData()
  },
})
